<?php
class NewsController extends CalendarAppController {

	var $name = 'News';

	var $permissions = array(
		'index' => array('admin','manag'),
		'edit' => array('admin','manag'),
		'delete' => array('admin','manag'),
		'view' => '*',
		'display' => '*'		
	);
	
	public function beforeFilter(){
		parent::beforeFilter();
		$this->layout = 'cms';	
	}
	
	function beforeRender(){
		parent::beforeRender();
		// nazwa strony i keywords
		$this->setup_page();		
	}
	
	function afterFilter(){
		parent::afterFilter();		
	}
	
	private function setup_page(){
//		if ($this->params['action'] == 'view' && isset($this->params['pass'][0])){
//			$this->StoreProduct->recursive = 0;
//			$storeProduct = $this->StoreProduct->read(null, $this->params['pass'][0]);
//			
//
//			if($storeProduct['StoreProduct']['price_przecena'] > 0 && $storeProduct['StoreProduct']['price_promocja'] == 0){
//				$price = $storeProduct['StoreProduct']['price_przecena'].' '.$storeProduct['StoreProduct']['currency_id'];
//			}else if( $storeProduct['StoreProduct']['price_promocja'] > 0){
//				$price = $storeProduct['StoreProduct']['price_promocja'].' '.$storeProduct['StoreProduct']['currency_id'];
//			}else{
//				$price = $storeProduct['StoreProduct']['price_detaliczna'].' '.$storeProduct['StoreProduct']['currency_id'];
//			}
//						
//			$title = $storeProduct['StoreProduct']['name'] . ' - ' . $price;
//			$this->set("title_for_layout",$title);
//			$this->set('keywords_for_layout_cms',$storeProduct['StoreProduct']['keywords']);
//		}else{
//			return false;
//		}		
	}	
	

	
	function display($group_id = null) {
		$this->News->recursive = 0;
		$this->News->recursive = 0;
		$conditions = array();
		if(!is_null($group_id)){
				$conditions['News.new_group_id'] = $group_id;
		}
		$years = $this->News->find('list',
				array(
					'conditions'=>$conditions,
					'fields'=>array('News.on_date','News.on_date'),
					'group'=>'strftime(\'%Y\',News.on_date)',
					'order'=>array('News.on_date'=>'DESC')
				)
			);		
		$conditions = array();
		if (!empty($this->data)) {			
			$conditions = array("strftime('%Y-%m-%d',News.on_date) BETWEEN  ? AND ?"=> array($this->data['News']['news_from_date'],$this->data['News']['news_to_date']));
		}
		$news = array();
		$conditions = array();
		foreach ($years as $year => $value) {
			$year = Date('Y',strtotime($year));
			$conditions = array('strftime(\'%Y\',News.on_date)' => $year);
			if(!is_null($group_id)){
				$conditions['News.new_group_id'] = $group_id;
			}
			$events = $this->News->find('all',
				array(
					'conditions' => $conditions,
					'order'=>array('News.on_date'=>'DESC')
				)
			);
			$news[$year] = $events;
		}		
		$this->set('news', $news);
		
		$newsGroups = $this->News->NewGroup->find('list');
		$this->set('newsGroups', $newsGroups);
		$this->set('selectedNewsGroups', $group_id);
				
		$this->layout = 'default';
		// wczytuje plik z theme
		$this->plugin = false;
	}
	
	function news($group_id = null) {
		$this->News->recursive = 0;
		$conditions = array('News.new_group_id'=>2);
	
		$this->paginate = array('order'=>array('News.on_date'=>'DESC'),'conditions'=>$conditions);
		$this->set('news', $this->paginate());
		$this->layout = 'default';
		// wczytuje plik z theme
		$this->plugin = false;
	}
	
	function events($group_id = null){
		Configure::write('debug', 0);
		$this->autoRender = false;

		App::import('Helper', 'html');
        $html = new HtmlHelper();
		App::import('Helper', 'text');
        $Text = new TextHelper();        
        
		$year = date('Y');
//		$month = (isset($this->params['named']['month'])) ? $this->params['named']['month'] : date('m');
////		$this->log($month,'calendar');
//		$month = ($month <= 9 ) ? '0'.$month : $month;
		$events_ = $this->News->find('all',
				array(
					'fields'=>array('News.id','News.name','News.on_date'),
					//'conditions'=>array('News.new_group_id'=>$group_id,'strftime(\'%Y\',News.on_date)'=>$year)
					'conditions'=>array('News.new_group_id'=>$group_id)
				)
			);
		$events = array();
		foreach ($events_ as $key => $e) {
			$name = $Text->truncate(
			    $e['News']['name'],
			    60,
			    array(
			        'ending' => '...',
			        'exact' => false
			    )
			);			
			$events[$key] = array('id'=>$e['News']['id'],'title'=>$name,'start'=>$e['News']['on_date'],'url'=>$html->url(array('plugin'=>'calendar','controller'=>'news','action'=>'view',$e['News']['id'])));
		}
		echo json_encode($events);

	}

	function view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid news', true));
			$this->redirect(array('action' => 'index'));
		}
		$newsGroups = $this->News->NewGroup->find('list');
		$this->set('newsGroups', $newsGroups);
		$news = $this->News->read(null, $id);
		$this->set('news', $news);
		$this->set('selectedNewsGroups', 0);
		$this->layout = 'default';
	}
	
	function one_news($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid news', true));
			$this->redirect(array('action' => 'index'));
		}
		$this->set('news', $this->News->read(null, $id));
		$this->layout = 'default';
	}	
	
	function index() {
		$this->News->recursive = 0;
		$this->set('news', $this->paginate());
	}

	function add() {
		if (!empty($this->data)) {
			if($this->FileUpload->success){
				$this->data['News']['new_upload_id'] = $this->News->NewUpload->getLastInsertID();				
			}
			$this->data['News']['added'] = date('Y-m-d H:i:s');
			$this->News->create();
			if ($this->News->save($this->data)) {
				$this->Session->setFlash(__('The news has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The news could not be saved. Please, try again.', true));
			}
		}
		$newsUploads = $this->News->NewUpload->find('list');
		$newsGroups = $this->News->NewGroup->find('list');
		$this->set(compact('newsUploads','newsGroups'));
	}

	function edit($id = null) {
		if (!$id && empty($this->data)) {						
			$this->Session->setFlash(__('Invalid news', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if($this->FileUpload->success){	
				$news = $this->News->findById($id);
	    		$this->News->NewUpload->delete($news['News']['new_upload_id']);
	    		$this->delete_file($news['News']['new_upload_id']);	
	    		$this->data['News']['new_upload_id'] = $this->News->NewUpload->getLastInsertID();	    		
			}			
			if ($this->News->save($this->data)) {
				$this->Session->setFlash(__('The news has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The news could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->News->read(null, $id);
		}
		$newsUploads = $this->News->NewUpload->find('list');
		$newsGroups = $this->News->NewGroup->find('list');
		$this->set(compact('newsUploads','newsGroups'));
	}

	function delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for news', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->News->delete($id)) {
			$this->Session->setFlash(__('News deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('News was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
	
	private function delete_file($upload_id = null) {
	    $upload =  $this->News->NewUpload->findById($upload_id);	    
	    if($this->FileUpload->removeFile($upload['NewUpload']['name'])){
			if($this->News->NewUpload->delete($upload['NewUpload']['id'])){
	        	$this->Session->setFlash(__d('calendar','File deleted', true));
			}else{
				$this->Session->setFlash(__d('calendar','The picture could not be deleted from Upload. Please, try again.', true));
			}
	    }else{
	    	$this->Session->setFlash(__d('calendar','The picture could not be deleted from Disc. Please, try again.', true));
	    }
	}
}
?>